package com.authine.cloudpivot.service;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.authine.cloudpivot.web.api.exception.PortalException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class CjfxOpenApiService2 {

    @Autowired
    private RestTemplate restTemplate;

    private static final String GET_TOKEN_URL = "https://fanqier.cn/openapi/get_token";

    private static final String APP_ID = "6545c6d294605d74b63e9a04";

    private static final String APP_SECRET = "NfWqzAvZRPgwsmjUEleU";

    private static final String GET_FROM_BY_ID = "https://fanqier.cn/openapi/forms/{id}/datas?access_token={access_token}&page={page}&pagesize={pagesize}&start={start}&end={end}";

    private static final String FORM_ID = "6544e4763385a5574da32fbb";

    //旧key  8f5c7fd086c87346f5997bcae76a1b1b
    //新key  e73f6db2126e3282204a765f65c405f8
    //昊天   5c744d31b4dab34f26505155df886caf
    //企业   c0084a40857f07328443ea40852d876e
    private static final String GET_ADDRESS_URL = "https://restapi.amap.com/v3/geocode/regeo?output=json&location={location}&key=5c744d31b4dab34f26505155df886caf&radius=1000&extensions=all";

    private static final String CONVERT_URL="https://restapi.amap.com/v3/assistant/coordinate/convert?locations={location}&coordsys=gps&output=json&key=5c744d31b4dab34f26505155df886caf";

    //地址编码
    private static final String GEO_URL="https://restapi.amap.com/v3/geocode/geo?address={addressName}&output=json&key=5c744d31b4dab34f26505155df886caf";


    public JSONObject getAddress(String location) {
        ResponseEntity<String> response = restTemplate.getForEntity(GET_ADDRESS_URL, String.class, location);
        if (Objects.isNull(response) || StringUtils.isBlank(response.getBody())) {
            log.error("CjfxOpenApiService:getAddress:response or response.body is blank!");
            return null;
        }
        JSONObject data = JSONUtil.parseObj(response.getBody());
        return data;
    }

    public JSONObject convert(String location){
        ResponseEntity<String> response = restTemplate.getForEntity(CONVERT_URL, String.class, location);
        if (Objects.isNull(response) || StringUtils.isBlank(response.getBody())) {
            log.error("CjfxOpenApiService:getAddress:response or response.body is blank!");
            return null;
        }
        JSONObject data = JSONUtil.parseObj(response.getBody());
        return data;
    }

    public JSONObject geo(String addressName){
        ResponseEntity<String> response = restTemplate.getForEntity(GEO_URL, String.class, addressName);
        if (Objects.isNull(response) || StringUtils.isBlank(response.getBody())) {
            log.error("CjfxOpenApiService:getAddress:response or response.body is blank!");
            return null;
        }
        JSONObject data = JSONUtil.parseObj(response.getBody());
        return data;
    }


    public InputStream downloadImage(String fileUrl) {
        InputStream inputStream = null;
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
        } catch (IOException e) {
            log.error("CjfxOpenApiService:downloadImage:get inputStrem form fileUrl error,fileUrl:{},msg:{}", fileUrl, e);
        }
        return inputStream;
    }


    public JSONObject getFormById(Integer page, Integer pageSize, Long start, Long end) {
        Map<String, Object> params = new HashMap<>(3);
        params.put("id", FORM_ID);
        params.put("access_token", getAccessToken());
        params.put("page", page);
        params.put("pagesize", pageSize);
        params.put("start", start);
        params.put("end", end);
        ResponseEntity<JSONObject> response = restTemplate.getForEntity(GET_FROM_BY_ID, JSONObject.class, params);
        if (Objects.isNull(response) || MapUtils.isEmpty(response.getBody())) {
            log.error("CjfxOpenApiService:getFromById:response or response.body is blank!");
            return null;
        }
        JSONObject body = response.getBody();
        JSONObject status = body.getJSONObject("status");
        JSONObject data = body.getJSONObject("data");
        if (MapUtils.isNotEmpty(status) && "200".equals(status.getStr("code"))) {
            return data;
        }
        log.info("CjfxOpenApiService:getFromById:status:{}", status);
        return null;
    }


    public String getAccessToken() {
        HashMap<String, String> params = new HashMap<>(2);
        params.put("appId", APP_ID);
        params.put("appSecret", APP_SECRET);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set(HttpHeaders.CONTENT_TYPE, "application/json");
        HttpEntity<Object> httpEntity = new HttpEntity<>(params, httpHeaders);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(GET_TOKEN_URL, httpEntity, JSONObject.class);
        if (Objects.isNull(response) || MapUtils.isEmpty(response.getBody())) {
            throw new PortalException(-1L, "getAccessToken : response or response.body is blank!");
        }
        JSONObject body = response.getBody();
        JSONObject data = body.getJSONObject("data");
        if (MapUtils.isEmpty(data)) {
            throw new PortalException(-1L, "body.data is blank!");
        }
        String accessToken = data.getStr("access_token");
        if (StringUtils.isBlank(accessToken)) {
            throw new PortalException(-1L, "accessToken id blank!");
        }
        log.info("CjfxOpenApiService:getAccessToken:accessToken:{}", accessToken);
        return accessToken;
    }

    public static void main(String[] args) {
        CjfxOpenApiService2 cjfxOpenApiService = new CjfxOpenApiService2();
        InputStream inputStream = cjfxOpenApiService.downloadImage("https://qn.fqcdn.cn/20231104134905-452971.jpg");
        if (!Objects.isNull(inputStream)) {
            return;
        }
    }

}
